<?php
/**
 * @link http://www.yiiframework.com/
 * @copyright Copyright (c) 2008 Yii Software LLC
 * @license http://www.yiiframework.com/license/
 */

namespace common\helpers\Log;

use Yii;
use yii\db\Connection;
use yii\helpers\VarDumper;

/**
 * DbTarget stores log messages in a database table.
 *
 * The database connection is specified by [[db]]. Database schema could be initialized by applying migration:
 *
 * ```
 * yii migrate --migrationPath=@yii/log/migrations/
 * ```
 *
 * If you don't want to use migration and need SQL instead, files for all databases are in migrations directory.
 *
 * You may change the name of the table used to store the data by setting [[logTable]].
 *
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */
class DbTarget extends \yii\log\DbTarget {
    /**
     * Stores log messages to DB.
     */
    public function export() {
        $tableName = $this->db->quoteTableName($this->logTable);
        $sql       = "INSERT INTO $tableName ([[level]], [[category]], [[log_time]], [[prefix]], [[message]], [[operator_id]], [[operator_name]])
                VALUES (:level, :category, :log_time, :prefix, :message, :operator_id, :operator_name)";
        $command = $this->db->createCommand($sql);
        foreach ($this->messages as $message) {
            list($text, $level, $category, $timestamp) = $message;
            if (!is_string($text)) {
                // exceptions may not be serializable if in the call stack somewhere is a Closure
                if ($text instanceof \Exception) {
                    $text = (string) $text;
                } else {
                    $text = VarDumper::export($text);
                }
            }
            $command->bindValues([
                ':level'         => $level,
                ':category'      => $category,
                ':log_time'      => $timestamp,
                ':prefix'        => $this->getMessagePrefix($message),
                ':message'       => $text,
                ':operator_id'   => \common\models\User::getIsLogined() ? \common\models\User::getLoginedModel()->id : '',
                ':operator_name' => \common\models\User::getIsLogined() ? \common\models\User::getLoginedModel()->name : 0,
            ])->execute();
        }
    }
}
